package com.tsfyun.common.base.util;

import com.google.common.base.CaseFormat;
import org.springframework.util.ClassUtils;

import java.lang.reflect.Field;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

/**
 * @Description:
 * @since Created in 2019/12/12 18:43
 */
public class ClassUtil {

    /**
     * 判断是否是简单值类型.包括：基础数据类型、CharSequence、Number、Date、URL、URI、Locale、Class;
     *
     * @param clazz
     * @return
     */
    public static boolean isSimpleValueType(Class<?> clazz) {
        return (ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() || CharSequence.class.isAssignableFrom(clazz)
                || Number.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || URI.class == clazz
                || URL.class == clazz || Locale.class == clazz || Class.class == clazz);
    }

    /**
     * 判断某个类是否包含某属性
     * @param clazz
     * @param fieldName
     * @return
     */
    public static boolean containsField(Class<?> clazz, String fieldName) {
        //如果传的不是驼峰，转驼峰
        final String underFieldName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,fieldName);
        Field[] declaredFields = clazz.getDeclaredFields();
        if (clazz.getSuperclass() != null) {
            Field[] superField = clazz.getSuperclass().getDeclaredFields();
            if(Objects.nonNull(superField) && superField.length > 0) {
                declaredFields = ArrayUtil.concatAll(declaredFields,superField);
            }
        }
        return Arrays.asList(declaredFields).stream().filter(r->Objects.equals(r.getName(),underFieldName)).count() > 0;
    }

}
